package com.yuntian.Handler;


import com.yuntian.exception.BaseException;
import com.yuntian.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

    /**
     * 捕获SQL异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
        String message = ex.getMessage();
        if(message.contains("Duplicate entry")){
            String[] split = message.split("");
            String username = split[2];
            String msg = username + "账号已存在";
            return Result.error(msg);
        }
        return Result.error("未知错误");
    }

    /**
     * 捕获Spring Security权限不足异常
     * @param ex
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    public Result handleAccessDeniedException(AccessDeniedException ex) {
        log.error("权限不足: {}", ex.getMessage());
        return Result.error("权限不足，无法执行此操作");
    }

    /**
     * 捕获Spring Security认证异常
     * @param ex
     * @return
     */
    @ExceptionHandler(AuthenticationException.class)
    public Result handleAuthenticationException(AuthenticationException ex) {
        log.error("认证失败: {}", ex.getMessage());
        return Result.error("认证失败，请重新登录");
    }

}
